package com.qyhl.webtv.module_news.news.titlenews;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;

import com.gyf.immersionbar.ImmersionBar;
import com.just.library.AgentWeb;
import com.just.library.WebDefaultSettingsManager;
import com.just.library.WebSettings;
import com.qyhl.cloud.webtv.module_news.R;
import com.qyhl.cloud.webtv.module_news.R2;
import com.qyhl.webtv.basiclib.base.BaseFragment;
import com.qyhl.webtv.basiclib.utils.MPermissionUtils;
import com.qyhl.webtv.basiclib.utils.Md5Builder;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.utils.MShareBoard;
import com.qyhl.webtv.commonlib.utils.eventbus.BusFactory;
import com.qyhl.webtv.commonlib.utils.eventbus.Event;
import com.qyhl.webtv.commonlib.utils.share.ShareUtils;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.weavey.loading.lib.LoadingLayout;

import java.io.File;
import java.util.ArrayList;

import butterknife.BindView;
import es.dmoral.toasty.Toasty;

/**
 * Created by qyhl on 2017/12/14.
 */

public class TitleNewsFragment extends BaseFragment implements TitleNewsContract.TitleNewsView {
    @BindView(R2.id.back)
    ImageView back;
    @BindView(R2.id.share_btn)
    ImageView shareBtn;
    @BindView(R2.id.title)
    TextView mTitle;
    @BindView(R2.id.barlayout)
    RelativeLayout barlayout;
    @BindView(R2.id.web_layout)
    LinearLayout webLayout;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;
    private String title;

    private TitleNewsPresenter mPresenter;
    private String mUrl;
    private String logo;
    private boolean hasShare = true;

    private String newsId;
    private WebView mWebView;

    public void setTitle(String title) {
        this.title = title;
    }

    public void setmUrl(String mUrl) {
        this.mUrl = mUrl;
    }

    public void setNewsId(String newsId) {
        this.newsId = newsId;
    }

    public void setLogo(String logo) {
        this.logo = logo;
    }

    public void setHasShare(boolean hasShare) {
        this.hasShare = hasShare;
    }

    public static final int FILECHOOSER_RESULTCODE_5 = 12;
    public static final int FILECHOOSER_RESULTCODE = 13;
    public WebChromeClient.FileChooserParams mfileChooserParams;
    public ValueCallback<Uri[]> umUploadMessages;
    public ValueCallback<Uri> mUploadMessage;

    private boolean hasJS;

    public void setHasJS(boolean hasJS) {
        this.hasJS = hasJS;
    }


    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.news_fragment_link, null);
    }

    @Override
    protected void create() {
        mPresenter = new TitleNewsPresenter(this);

        loadData();
    }


    @Override
    protected void setListener() {

    }

    @Override
    public void initImmersionBar() {
        if (!StringUtils.isEmpty(title)) {
            ImmersionBar.with(this)
                    .fitsSystemWindows(true)
                    .statusBarDarkFont(true)
                    .statusBarColor(R.color.white)
                    .init();
        }
    }

    public static TitleNewsFragment newInstance(String title, String url) {
        TitleNewsFragment fragment = new TitleNewsFragment();
        fragment.setTitle(title);
        fragment.setmUrl(url);
        return fragment;
    }

    public static TitleNewsFragment newInstance(String title, String url, String id, String logo, boolean hasShare) {
        TitleNewsFragment fragment = new TitleNewsFragment();
        fragment.setTitle(title);
        fragment.setmUrl(url);
        fragment.setNewsId(id);
        fragment.setLogo(logo);
        fragment.setHasShare(hasShare);
        return fragment;
    }

    public static TitleNewsFragment newInstance(String title, String url, String id, boolean hasJS) {
        TitleNewsFragment fragment = new TitleNewsFragment();
        fragment.setTitle(title);
        fragment.setmUrl(url);
        fragment.setNewsId(id);
        fragment.setHasJS(hasJS);
        return fragment;
    }


    /**
     * 加载数据
     */
    private void loadData() {
        //下拉刷新
        initView();
        setListeners();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            if (mWebView != null) {
                mWebView.onResume();
            }
        } else {
            if (mWebView != null) {
                mWebView.onPause();
            }
        }
    }

    /**
     * 初始化
     */
    private void initView() {
        loadMask.setStatus(LoadingLayout.Loading);

        if (TextUtils.isEmpty(title)) {
            barlayout.setVisibility(View.GONE);
        } else {
            mTitle.setText(title);//设置标题
        }

        if (hasShare) {
            shareBtn.setVisibility(View.VISIBLE);
        } else {
            shareBtn.setVisibility(View.INVISIBLE);
        }

        WebViewClient mWebViewClient = new WebViewClient() {
            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.cancel();
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.startsWith("http:") || url.startsWith("https:")) {
                    return false;
                }
                try {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(intent);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                loadMask.setStatus(LoadingLayout.Success);

                if (hasJS) {
                    //安卓调用js方法。注意需要在 onPageFinished 回调里调用
                    String username = CommonUtils.getInstance().getUserName();
                    String s;
                    String s2;
                    if (StringUtils.isNotEmpty(username)) {
                        s = username;
                        s2 = Md5Builder.encode(username);
                    } else {
                        s = "";
                        s2 = "";
                    }

                    view.post(new Runnable() {
                        @Override
                        public void run() {
                            mWebView.evaluateJavascript("javascript:connect('" + s + "','" + s2 + "')", new ValueCallback<String>() {
                                @Override
                                public void onReceiveValue(String s) {
                                    Log.i("test", s);
                                }
                            });
                        }
                    });
                }
            }
        };


        WebChromeClient webChromeClient = new WebChromeClient() {
            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
                umUploadMessages = filePathCallback;
                mfileChooserParams = fileChooserParams;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                String[] acceptTypes = mfileChooserParams.getAcceptTypes();
                if (acceptTypes[0].equals("video/*")) {
                    i.setType("video/*");
                } else if (acceptTypes[0].equals("image/*")) {
                    i.setType("image/*");
                }
                startActivityForResult(Intent.createChooser(i, "选择相册"), FILECHOOSER_RESULTCODE_5);
                return true;
            }

            // For Android > 4.1
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                if (acceptType.equals("video/*")) {
                    i.setType("video/*");
                } else if (acceptType.equals("image/*")) {
                    i.setType("image/*");
                }
                startActivityForResult(Intent.createChooser(i, "选择相册"),
                        FILECHOOSER_RESULTCODE);
            }
        };


        AgentWeb mAgentWeb = AgentWeb.with(this)
                .setAgentWebParent(webLayout, new LinearLayout.LayoutParams(-1, -1))//传入AgentWeb 的父控件 ，如果父控件为 RelativeLayout ， 那么第二参数需要传入 RelativeLayout.LayoutParams
                .useDefaultIndicator()// 使用默认进度条
                .setWebSettings(new CustomSettings())
                .setWebViewClient(mWebViewClient)
                .setWebChromeClient(webChromeClient)
                .setReceivedTitleCallback((view, title) -> {

                })//设置 Web 页面的 title 回调
                .createAgentWeb()//
                .ready()
                .go(mUrl);


        mWebView = mAgentWeb.getWebCreator().get();

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mWebView.reload();
            }
        },500);

        if (StringUtils.isNotEmpty(newsId)) {
            shareBtn.setImageResource(R.drawable.new_details_more_icon);
            mPresenter.count(newsId);
        }
    }

    /**
     * 设置监听
     */
    private void setListeners() {
        //返回键监听
        back.setOnClickListener(v -> {
            if (mWebView != null && mWebView.canGoBack()) {
                mWebView.goBack();
            } else {
                BusFactory.getBus().post(new Event.finishActivity());
            }
        });

        //分享按钮监听
        shareBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MPermissionUtils.requestPermissionsResult(getActivity(), 1, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, new MPermissionUtils.OnPermissionListener() {
                    @Override
                    public void onPermissionGranted() {
                        if (StringUtils.isEmpty(newsId)) {
                            ShareUtils.getInstance().doShare(getActivity(), mUrl, title, "", "", new UMShareListener() {
                                @Override
                                public void onStart(SHARE_MEDIA share_media) {

                                }

                                @Override
                                public void onResult(SHARE_MEDIA share_media) {
                                    Toasty.normal(getContext(), "分享成功！", Toast.LENGTH_SHORT).show();
                                }

                                @Override
                                public void onError(SHARE_MEDIA share_media, Throwable throwable) {
                                    Toasty.normal(getContext(), "分享失败！", Toast.LENGTH_SHORT).show();
                                }

                                @Override
                                public void onCancel(SHARE_MEDIA share_media) {

                                }
                            });
                        } else {
                            MShareBoard shareBoard = new MShareBoard(getActivity(), newsId, title, logo, "", 8, true);
                            shareBoard.showPopupWindow();
                        }

                    }

                    @Override
                    public void onPermissionDenied() {
                        MPermissionUtils.showTipsDialog(getContext());
                    }
                });
            }
        });
    }

    @Override
    protected void onFirstVisible() {

    }

    @Override
    protected void onVisible() {

    }

    @Override
    protected void onHide() {

    }

    class CustomSettings extends WebDefaultSettingsManager {
        CustomSettings() {
            super();
        }


        @Override
        public WebSettings toSetting(WebView webView) {
            super.toSetting(webView);
            String path = Environment.getExternalStorageDirectory().getPath() + "/baidudata";//百度地图调用需要
            File tmpFile = new File(path);
            if (!tmpFile.exists()) {
                tmpFile.mkdirs();
            }
            getWebSettings().setCacheMode(android.webkit.WebSettings.LOAD_NO_CACHE);
            getWebSettings().setGeolocationDatabasePath(path);
            getWebSettings().setDomStorageEnabled(true);
            getWebSettings().setBlockNetworkImage(false);//是否阻塞加载网络图片  协议http or https
            getWebSettings().setAllowFileAccess(false); //允许加载本地文件html  file协议, 这可能会造成不安全 , 建议重写关闭
            getWebSettings().setAllowFileAccessFromFileURLs(false); //通过 file url 加载的 Javascript 读取其他的本地文件 .建议关闭
            getWebSettings().setAllowUniversalAccessFromFileURLs(false);//允许通过 file url 加载的 Javascript 可以访问其他的源，包括其他的文件和 http，https 等其他的源
            getWebSettings().setUseWideViewPort(true);
            getWebSettings().setSupportZoom(true);
            getWebSettings().setBuiltInZoomControls(true);
            getWebSettings().setJavaScriptEnabled(true);
            if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP){
                getWebSettings().setMixedContentMode(android.webkit.WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
            }
            return this;
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        MPermissionUtils.onRequestPermissionsResult(requestCode, permissions, grantResults);
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public void onResume() {
        if (mWebView != null) {
            mWebView.onResume();
        }
        super.onResume();
        //baidu
        //umeng
        MobclickAgent.onPageStart("底部链接");
        MobclickAgent.onResume(getContext());
    }

    @Override
    public void onPause() {
        if (mWebView != null) {
            mWebView.onPause();
        }
        super.onPause();
        //baidu
        //umeng
        MobclickAgent.onPageEnd("底部链接");
        MobclickAgent.onPause(getContext());
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mWebView != null) {
            mWebView.destroy();
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == FILECHOOSER_RESULTCODE) {
            if (null == mUploadMessage) return;
            if (null == data) {
                mUploadMessage.onReceiveValue(null);
                mUploadMessage = null;
            } else {
                Uri result = data == null || resultCode != Activity.RESULT_OK ? null : data.getData();
                mUploadMessage.onReceiveValue(result);
                mUploadMessage = null;
            }
        } else if (requestCode == FILECHOOSER_RESULTCODE_5) {// 5.0适配，主要是因为5.0的返回参数不同。
            // 处理5.0的callback
            if (umUploadMessages != null) {
                if (null != data) { // 5.0的处理方式不同，要注意。
                    ArrayList<String> resultList = data.getStringArrayListExtra("data");
                    umUploadMessages.onReceiveValue(mfileChooserParams.parseResult(resultCode, data));
                    umUploadMessages = null;
                } else {
                    umUploadMessages.onReceiveValue(null);
                }
            }
        }
    }


}
